package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"huxiaopang/models"
)

type NotifyController struct {
	ApiBaseController
}

// @router /notifyresult [post]
func (this *NotifyController) NotifyResult() {
	beego.Debug("推送服务")
	bean := BaseBean{}
	var sendHookBean SendHookBean
	json.Unmarshal(this.Ctx.Input.RequestBody, &sendHookBean)
	beego.Debug(sendHookBean)

	if len(sendHookBean.DownTradeNo) == 0 {
		bean.Code = "-1"
		bean.Message = "down_trade_no不能为空"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	}

	tradeData := models.TradeData{}
	tradeData.DownTradeNo = sendHookBean.DownTradeNo
	if err := tradeData.Read("DownTradeNo"); err != nil {
		bean.Code = "-1"
		bean.Message = "该订单不存在"
		this.Data["json"] = bean
		this.ServeJSON()
		return
	} else {
		//推送
		tradeData.RequestId = sendHookBean.RequestId
		tradeData.TradeNo = sendHookBean.TradeNo
		tradeData.UpTradeNo = sendHookBean.PayChannelTradeNo
		tradeData.TradeStatus = sendHookBean.TradeStatus
		tradeData.TradeChannel = sendHookBean.TradeChannel
		tradeData.PayAmount = sendHookBean.PayAmount
		tradeData.ReceiptAmount = sendHookBean.ReceiptAmount
		tradeData.BuyerAmount = sendHookBean.BuyerAmount
		tradeData.BuyerUserId = sendHookBean.BuyerUserId
		tradeData.BuyerUserName = sendHookBean.BuyerUserName
		tradeData.OpenId = sendHookBean.OpenId
		tradeData.SubOpenId = sendHookBean.SubOpenId
		tradeData.StoreCode = sendHookBean.StoreCode
		tradeData.RawData = sendHookBean.RawData
		tradeData.CreateTime = sendHookBean.CreateTime
		tradeData.PayTime = sendHookBean.PayTime
		if err := tradeData.Update("RequestId", "TradeNo", "UpTradeNo", "TradeStatus", "TradeChannel", "PayAmount",
			"ReceiptAmount", "BuyerAmount", "BuyerUserId", "BuyerUserName", "OpenId", "SubOpenId", "StoreCode", "RawData", "CreateTime", "PayTime"); err != nil{
		// for a := 0; a < 10; a++ {
			beego.Debug("notify update error" + sendHookBean.DownTradeNo)
			this.Ctx.WriteString("ERROR")
			return
		// }	
		}else{
			pushData(sendHookBean.StoreCode, tradeData.TableCode ,sendHookBean.TradeNo)
			this.Ctx.WriteString("SUCCESS")
			return
		}
		// deviceTableCodeData := models.DeviceTableCodeData{}
		// deviceTableCodeData.StoreCode = sendHookBean.StoreCode
		// deviceTableCodeData.TableCode = tradeData.TableCode
		// if err := deviceTableCodeData.Read("StoreCode", "TableCode"); err != nil {
		// 	beego.Debug("notifyresult tcp push" + err.Error())
		// }else {
		// 	beego.Debug("notifyresult tcp push" + sendHookBean.StoreCode + ":" + tradeData.TableCode)
		// 	for a := 0; a < 50; a++{
		// 		tcpPushData(sendHookBean.StoreCode, deviceTableCodeData.DeviceId, sendHookBean.TradeNo, strconv.Itoa(a))
		// 	}
		// }

	}

	this.Ctx.WriteString("SUCCESS")
	return

}
